<?php

namespace App\Http\Controllers\RBAC;

use App\User;
use App\RBAC\Role;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $request->session()->put('status', 'current_user:'.Auth::user());
        return view('rbac/user');
    }

    public function apiIndex(Request $request)
    {
        if($request->role_id){
            $paginateData=User::where('role_id',$request->role_id)->paginate(intval($request->per_page));
        }else{
            $paginateData=User::orderBy('id',"ASC")->paginate(intval($request->per_page)); 
        }        
        $roles=Role::get();
        foreach ($paginateData as $key => $value) {
            $tmp=$value->role;
         }
        $data['data']=$paginateData;
        $data['roles']=$roles;
        return $data;
    }

    public function apiDelete(Request $request,User $user)
    {
        if($user->delete()){
            return ['msg'=>'ok'];
        }else{
            return ['msg'=>'fail'];
        }
    }

    public function apiStore(Request $request)
    {
        if($request->id){
            $group = User::findOrFail(intval($request->id));
            $group->name=$request->name;
            $group->role_id=$request->role_id;
            $group->email=$request->email;
            if($request->password){
                $group->password = Hash::make($request->password);
            }
            if($group->save()){
                $group = User::findOrFail(intval($request->id));
            }
        }else{
            $group = User::firstOrCreate(['name' => $request->name,'email' => $request->email,'role_id'=>$request->role_id,'password'=>Hash::make($request->password)]);
        }
        $tmp=$group->role;
        return $group;
    }
}
